package com.hnyc.controller;

import com.hnyc.domain.AjaxResult;
import com.hnyc.domain.CandConstants;
import com.hnyc.domain.CandUser;
import com.hnyc.service.ICandUserService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: XieYingHao
 * @date: 2023/7/1 11:01
 */
@RestController
@RequestMapping("/cand/user")
public class CandUserController {

    @Resource
    private ICandUserService candUserService;

    /**
     * 新增用户
     */
    @PostMapping
    public AjaxResult add(@Validated @RequestBody CandUser user) {
        if (CandConstants.NOT_UNIQUE.equals(candUserService.checkUserNameUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        return candUserService.insertUser(user) > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 修改用户
     */
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody CandUser user) {

        if (CandConstants.NOT_UNIQUE.equals(candUserService.checkUserNameUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，账号已存在");
        }
        return candUserService.updateUser(user) > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 获取用户列表
     */
    @GetMapping("/list")
    public AjaxResult list(CandUser user) {
        List<CandUser> list = candUserService.selectUserList(user);
        return AjaxResult.success(list);
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{userId}")
    public AjaxResult remove(@PathVariable Long userId)
    {
        return candUserService.deleteUserById(userId) > 0 ? AjaxResult.success() : AjaxResult.error();
    }
}
